package com.xixibaby.validator;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ResolverBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if(bean instanceof RequestMappingHandlerAdapter){
            RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter)bean;
            XixibabyRequestResponseBodyMethodProcessor xixibabyRequestResponseBodyMethodProcessor = new XixibabyRequestResponseBodyMethodProcessor(adapter.getMessageConverters());

            List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
            resolvers.add(xixibabyRequestResponseBodyMethodProcessor);
            resolvers.addAll(Objects.requireNonNull(adapter.getArgumentResolvers()));
            adapter.setArgumentResolvers(resolvers);
        }
        return bean;
    }
}